<template>
  <div class="billBottom">
    <div style="padding-left: 5px; display: flex">
      <div style="flex: 1;">
        <j-space>
          <JButton :size="'medium'" style="margin-right: 30px" @click="handleClick('add')" text="新增(F12)" />
          <JButton
            type="info"
            :loading="load.loading"
            :size="'medium'"
            @click="handleClick('save')"
            :disabled="billState !== 'ready' && billState !== 'draft'"
            text="保存草稿(F1)"
            style="margin-right: 10px;"
          />
          <JButton
            style="margin-right: 10px;"
            :loading="load.loading"
            :size="'medium'"
            :disabled="billState !== 'ready' && billState !== 'draft'"
            @click="handleClick('accounted')" text="审核(F2)"
          />
          <JButton
              style="margin-right: 10px;"
              :loading="load.loading"
              :size="'medium'"
              :disabled="billState !== 'accounted'"
              @click="handleClick('wasted')"
              text="退审(F3)"
              confirm
              confirm-text="确定退审？"
          />
          <div  style="margin-left: 10px;">
            <tiny-dropdown
                split-button
                size="medium"
                :disabled="canPrint"
                @item-click="itemClick"
                trigger="click"
            >
              <template #default>
                <tiny-button :disabled="canPrint"  type="text" :loading="load.loading" @click="handleClick('print')">直接打印(F4)</tiny-button>
              </template>
              <template #dropdown>
                <tiny-dropdown-menu>
                  <tiny-dropdown-item>打印预览(ctrl+p)</tiny-dropdown-item>
                </tiny-dropdown-menu>
              </template>
            </tiny-dropdown>
          </div>
        </j-space>
      </div>
      <div>
        <JButton type="text" :disabled="billState === 'ready'" @click="handleClick('copy')">复制(F8)</JButton>
        <JButton type="text" v-if="showHist"  @click="handleClick('f9')">导出(F9)</JButton>
        <JButton type="text" v-if="showHist"  @click="handleClick('f10')">价格(F10)</JButton>
        <JButton type="text" :disabled="billState !== 'draft'" @click="handleClick('del')">删除(F11)</JButton>
        <JButton type="text"  @click="handleClick('list')">列表</JButton>
        <div style="color: darkgray;font-size:13px;padding-left: 10px;padding-top: 5px;">
          <span>往来单位(alt+1)</span>
          <span style="margin-left: 10px;">表格单元(alt+2)</span>
        </div>

      </div>
      <input ref="hideInput" type="hidden" />
    </div>
  </div>
</template>

<script setup name="billBottomBtn">
import tool from "@/utils/tool";
import {ref, computed, onBeforeMount, onActivated, onDeactivated, onUnmounted, nextTick,} from "vue";
import {useGlobal} from "@/store/globalStore";
import {useRoute, useRouter} from "vue-router";
import { TinyPopconfirm } from '@opentiny/vue'
import router from "@/router";
const global = useGlobal();
const props = defineProps({
  billRules: {type: Array, default: function () {return []}}, // 按钮参数
  infoBak: {type: Array, default: function () {return []}}, // 按钮参数
  model: {type: Object, default: function () {return {}}}, // 按钮参数
  listRoute: {type: String, default: ''}, // 按钮参数
})
const route = useRoute()

const emit = defineEmits([ 'refresh', 'toList'])
const load = ref({
  loading: false
})
const opt = ref({})
const fApi = ref({})
const printAfterAccounted = computed(() => {
  return opt.value.printAfterAccounted
})
const hideInput = ref()
const hideInputFocus = () => {
  hideInput.value.focus()
  setTimeout(() => {
    hideInput.value.blur()
  }, 10)
}
const saveDraft = (model, type) => {
  if (model.billState !== 'ready' && model.billState !== 'draft') {
    tool.err('不能保存非草稿数据');
  }
  if (tool.dayjs(model.billDate).diff(tool.getDay(), 'days') > 0) {
    return tool.err('票据日期不能超过今天');
  }
  let saveAdd = global.systemParams.saveAdd;
  let accountedAdd = global.systemParams.accountedAdd;
  tool.post('bill/save', model, load.value).then((ret) => {
    if (ret.stat) {
      let data = ret.data;
      fApi.value.setValue('id', data.id)
      fApi.value.setValue('billState', 'draft')
      fApi.value.setValue('billNo', data.billNo)
      // 审核
      if (type === 'accounted') {
        let accdata = {
          byScan: 0,
          // menuId: currentMenuId,
          transType: model.transType,
          ids: [data.id],
        };
        tool.post('bill/toAccounted', accdata).then((ret) => {
          if (ret.stat) {
            fApi.value.setValue('billState', 'accounted')
            if (accountedAdd) {
              // 审核后新增
              formReset();
            }
            refresh();
          }
        });
      }
      else {
        if (saveAdd) {
          // 保存后自动新增
          formReset();
        }
        refresh();
      }
    }
  })
}
const valid = (callback) => {
  let model = tool.xe.clone(fApi.value.getFormData(), true);
  for (let i = 0; i < props.billRules.length; i++) {
    let row = props.billRules[i]
    if (row.props) {
      if (row.props.float) model[row.field] = tool.xe.toNumber(model[row.field])
      if (row.props.price) model[row.field] = tool.xe.toNumber(model[row.field])
    }
  }
  let infos = fApi.value.exec('infos', 'getData');
  if (!model.billDate) return tool.err('请选择开票日期');
  if (tool.dayjs(model.billDate).diff(tool.getDay(), 'days') > 0) {
    return tool.err('票据日期不能超过今天');
  }
  if (model.transType === 153201) {
    // 核销单
    let hxList = fApi.value.exec('hxList', 'getData');
    let billList = fApi.value.exec('billList', 'getData');
    let infos = [];
    let l1 = [];
    let l2 = [];
    hxList.map((row) => {
      row.listType = 'hxList';
      if (tool.xe.toNumber(row.nowCheck) !== 0) l1.push(row);
      if (tool.xe.toNumber(row.nowCheck) !== 0) infos.push(row);
    });
    billList.map((row) => {
      row.listType = 'billList';
      if (tool.xe.toNumber(row.nowCheck) !== 0) l2.push(row);
      if (tool.xe.toNumber(row.nowCheck) !== 0) infos.push(row);
    });
    if (l1.length === 0) {
      tool.err('没有核销数据');
      return;
    }
    if (l2.length === 0) {
      tool.err('没有核销数据');
      return;
    }
    let m1 = tool.xe.sum(l1, 'nowCheck');
    let m2 = tool.xe.sum(l2, 'nowCheck');
    if (m1 === 0) return tool.err('合计金额为 0 ');
    if (m2 === 0) return tool.err('合计金额为 0 ');
    if (m1 !== m2) {
      return tool.err('核销金额不等于应核销金额');
    }
    model.infos = infos;
    callback(model);
  }
  if (model.transType === 153403) {
    let ret = [];
    model.subRemark = '';
    let subRemark = [];
    for (let i = 0; i < infos.length; i++) {
      delete infos[i].id;
      let row = infos[i];
      if (row.invId && row.invName) {
        if (!row.spec) {
          tool.err('请输入第 ' + (i + 1) + ' 行规格');
          return;
        }
        if (!row.unit) {
          tool.err('请输入第 ' + (i + 1) + ' 行单位');
          return;
        }
        if (!row.qty) {
          tool.err('请输入第 ' + (i + 1) + ' 行数量');
          return;
        }
        if (!row.calNum) {
          tool.err('第 ' + (i + 1) + ' 行规格有误');
          return;
        }
        if (row.remark) {
          subRemark.push(row.remark);
        }
        ret.push(row);
      }
    }
    if (subRemark.length > 0) {
      model.subRemark = subRemark.join(',');
    }
    let total = tool.xe.sum(infos, 'amount');
    if (tool.add(model.accAmount, model.accAmount1) !== total) {
      return tool.err('合计金额不等于商品合计金额');
    }
    if (ret.length === 0) return tool.err('还没有商品列表');
    model.infos = ret;
    callback(model);
  }
  if (
      model.transType === 150501 ||
      model.transType === 150502 ||
      model.transType === 150601 ||
      model.transType === 150602 ||
      model.transType === 150603 ||
      model.transType === 150706 ||
      model.transType === 150806
  ) {
    let ret = [];
    let subRemark = [];
    if (model.accId && !model.rpAmount) {
      return tool.err('请输入结算金额');
    }
    if (model.rpAmount && !model.accId) {
      return tool.err('请选择结算账户');
    }
    for (let i = 0; i < infos.length; i++) {
      delete infos[i].id;
      let row = infos[i];
      if (row.invId && row.invName) {
        if (!row.spec) {
          tool.err('请输入第 ' + (i + 1) + ' 行规格');
          return;
        }
        if (!row.unit) {
          tool.err('请输入第 ' + (i + 1) + ' 行单位');
          return;
        }
        // 预收商品不用选择仓库
        if (model.billType !== 'YSG') {
          if (!row.locationId || !row.locationName) {
            tool.err('请输入第 ' + (i + 1) + ' 行仓库');
            return;
          }
        }
        if (!row.qty) {
          tool.err('请输入第 ' + (i + 1) + ' 行数量');
          return;
        }
        if (!row.calNum) {
          tool.err('第 ' + (i + 1) + ' 行规格有误');
          return;
        }
        if (row.remark) {
          subRemark.push(row.remark);
        }
        ret.push(row);
      }
    }
    model.subRemark = '';
    if (subRemark.length > 0) {
      model.subRemark = subRemark.join(',');
    }
    model.infos = ret;
    if (model.transType === 150603) {
      for (let i = 0; i < infos.length; i++) {
        if (infos[i].invId) {
          if (!infos[i].trans) {
            return tool.err('还没选择 类型');
          }
        }
      }
    }
    callback(model);
  }
  if (model.transType === 153001 || model.transType === 153101) {
    if (!model.buId || !model.buName) return tool.err('请选择终端客户');
    let ret = [];
    let subRemark = [];
    let billAmount = 0;
    if (infos.length > 0) {
      let grid = infos.filter((row) => {
        return row.billId;
      });
      if (grid.length > 0) {
        if (grid.length === 0) return tool.err('至少 1 行记录');
        for (let i = 0; i < grid.length; i++) {
          delete grid[i].id;
          let row = grid[i];
          if (!row.nowCheck) return tool.err('请输入 【' + row.srcBillNo + '】本次核销金额');
          row.nowCheck = tool.xe.toNumber(row.nowCheck);
          row.yhAmount = tool.xe.toNumber(row.yhAmount);
          row.leftAmount = tool.xe.toNumber(row.leftAmount);
          billAmount = tool.add(billAmount, row.nowCheck);
          ret.push(row);
          if (row.remark) {
            subRemark.push(row.remark);
          }
        }
      }
    }
    let total = tool.xe.add(model.accAmount, model.accAmount1);
    if (ret.length > 0) {
      if (total !== billAmount) {
        return tool.err('收款金额不等于核销票据金额');
      }
    }
    if (total === 0) {
      return tool.err('请输入收款金额');
    }
    model.infos = ret;
    model.amount = total;
    model.subRemark = '';
    if (subRemark.length > 0) model.subRemark = subRemark.join(',');
    callback(model);
  }
  // 其他收入 支出
  if (model.transType === 153401 || model.transType === 153402) {
    let ret = [];
    if (infos.length === 0) return tool.err('至少 1 行记录');
    let subRemark = [];
    for (let i = 0; i < infos.length; i++) {
      delete infos[i].id;
      let row = infos[i];
      if (row.subjectId) {
        subRemark.push(row.remark);
        if (!row.amount) return tool.err('请输入金额');
        ret.push(row);
      }
    }
    model.subRemark = '';
    if (subRemark.length > 0) model.subRemark = subRemark.join(',');
    model.infos = ret;
    callback(model);
  }
  // 应收 应付
  if (model.transType === 153404 || model.transType === 153405) {
    let ret = [];
    if (infos.length === 0) return tool.err('至少 1 行记录');
    let subRemark = [];
    for (let i = 0; i < infos.length; i++) {
      delete infos[i].id;
      let row = infos[i];
      if (row.accId) {
        subRemark.push(row.remark);
        if (!row.amount) return tool.err('请输入金额');
        ret.push(row);
      }
    }
    model.subRemark = '';
    if (subRemark.length > 0) model.subRemark = subRemark.join(',');
    model.infos = ret;
    callback(model);
  }
  // 预收 预付
  if (model.transType === 153406 || model.transType === 153407) {
    let ret = [];
    if (infos.length === 0) return tool.err('至少 1 行记录');
    let subRemark = [];
    for (let i = 0; i < infos.length; i++) {
      delete infos[i].id;
      let row = infos[i];
      if (row.accId) {
        subRemark.push(row.remark);
        if (!row.amount) return tool.err('请输入金额');
        ret.push(row);
      }
    }
    model.subRemark = '';
    if (subRemark.length > 0) model.subRemark = subRemark.join(',');
    model.infos = ret;
    callback(model);
  }
  if (model.transType === 160001) {
    let ret = [];
    if (infos.length === 0) return tool.err('至少 1 行记录');
    let subRemark = [];
    for (let i = 0; i < infos.length; i++) {
      delete infos[i].id;
      let row = infos[i];
      if (row.accId && row.accId1) {
        if (row.accId === row.accId1) return tool.err('转出账户等于转入账户');
        subRemark.push(row.remark);
        if (!row.amount) return tool.err('请输入金额');
        ret.push(row);
      }
    }
    model.subRemark = '';
    if (subRemark.length > 0) model.subRemark = subRemark.join(',');
    model.infos = ret;
    callback(model);
  }
  // 凭证
  if (model.billType === 'PZ') {
    let subRemark = [];
    let ret = [];
    for (let i = 0; i < infos.length; i++) {
      delete infos[i].id;
      let row = infos[i];

      if (!row.subjectId) continue;
      if (row.price1) if (!row.subjectId) return tool.err('请选择第 ' + (i + 1) + ' 行 科目');
      if (row.price2) if (!row.subjectId) return tool.err('请选择第 ' + (i + 1) + ' 行 科目');
      if (row.subjectId) {
        if (!row.price1 && !row.price2) {
          return tool.err('请输入第 ' + (i + 1) + '行 借方/贷方 金额');
        }
      }
      if (row.remark) subRemark.push(row.remark);
      ret.push(row);
    }
    let p1sum = tool.xe.sum(ret, 'price1');
    let p2sum = tool.xe.sum(ret, 'price2');

    if (p1sum !== p2sum) return tool.err('借方 不等于 贷方 ');
    model.subRemark = '';
    if (subRemark.length > 0) {
      model.subRemark = subRemark.join(',');
    }
    let g = ret.filter((row) => {
      return row.subjectId;
    });
    if (g.length < 2) return tool.err('至少 2 条记录');
    model.infos = ret;
    callback(model);
  }
}
const formReset = () => {
  fApi.value.resetFields();
  nextTick(() => {
    // fApi.value.setValue('infos', [])
    let da = tool.xe.clone(props.infoBak, true)
    fApi.value.setValue('infos', da)
    let transType = fApi.value.getValue('transType')
    if (transType === 153001 || transType === 153101) {
      let cat = '';
      let keyWord = '';
      if (transType === 153001) {
        cat = 'skCat';
        keyWord = '主营业务收入';
      }
      if (transType === 153101) {
        cat = 'fkCat';
        keyWord = '主营业务成本';
      }
      tool.post('common/dropdown', {cat, keyWord}, load.value).then((ret) => {
        if (ret) {
          fApi.value.setValue('subjectId', ret.data[0].id)
          fApi.value.setValue('subjectName', ret.data[0].name)
        }
      })
    }
  })
}


const billState = computed(() => {
  return props.model.billState
})
const showHist = computed(() => {
  return props.model.billType === 'PUR' || props.model.billType === 'SALE'
})

const canPrint = computed(() => {
  if(printAfterAccounted.value) {
    return billState.value === 'draft' || billState.value === 'ready' || billState.value === 'del'
  }
  else {
    return billState.value ==='ready' || billState.value === 'del'
  }
})

const refresh = () => {
  emit('refresh')
}
const toolClick = (type) => {
  hideInputFocus()
  switch (type) {
    case 'add': {
      // router.push({name: 's-in'})
      // //
      // window.history.replaceState('','','http://localhost:5173/main/s-in')
      formReset();
    }
      break;
    case 'gridFirstEmptyCell':{
      fApi.value.exec('infos', 'focusFirstCell', 'invName')
    }
          break
    case 'formFirstInput':{
      fApi.value.exec('buName','focus')
    }
          break
    case 'save': {

      if(fApi.value.valid()) {
        valid((model) => {
          saveDraft(model, type);
        })
      }
    }
    break
    case 'accounted': {
      if(fApi.value.valid()) {
        valid((model) => {
          saveDraft(model, type);
        })
      }
    }
      break;
    case 'copy': {
      tool.confirm('根据本单数据生成 1 张新票据 ？', '复制提示').then(() => {
        fApi.value.setValue('billState', 'ready')
        fApi.value.setValue('billNo', '')
        fApi.value.setValue('id', null)
      });
    }
      break;
    case 'wasted': {
      tool.post(
              'bill/toWasted',
              {
                ids: [fApi.value.getValue('id')],
                billType: fApi.value.getValue('billType'),
                transType: fApi.value.getValue('transType'),
                // menuId: currentMenuId,
              },
              load.value
          )
          .then((ret) => {
            if (ret.stat) {
              fApi.value.setValue('billState', 'draft')
              refresh();
            }
          })

    }
      break;
    case 'del': {
      let billState = fApi.value.getValue('billState')
      let id = fApi.value.getValue('id')
      let transType = fApi.value.getValue('transType')

      if (billState !== 'ready' && billState !== 'draft') tool.err('不能审核非草稿数据');
      let obj = {
        ids: [id],
        billState: 'del',
        transType: transType,
      };
      // obj.menuId = currentMenuId;
      tool.confirm('确定删除草稿 ？').then(() => {
        tool.post('bill/toDel', obj, load.value).then((ret) => {
          if (ret.stat) {
            formReset();
            refresh();
          }
        })
      })
    }
      break;
    case 'list': {
      // 开票界面路由到列表页面
      let menuList = tool.data.get('jsonMenu');
      let rname = route.name + 's';
      menuList.filter((row) => {
        return row.routeId === rname;
      });
    }
      break;
    case 'printView':
    case 'print': {
      let isCard = route.name === 'card';
      let printList = [{id: fApi.value.getValue('id')}];
      if (type === 'print') {
        tool.toPrint(printList, true, isCard);
        //
        // tool.confirm('是否打印 ？', '打印提示').then(() => {
        //   tool.toPrint(printList, true, isCard);
        // });

        // tool.post('print/detectStock', { transType: formModel.value.transType, ids: printList }).then((ret) => {
        //   if (ret.stat) {
        //     tool.confirm('是否直接打印 ？', '打印提示').then(() => {
        //       tool.toPrint(printList, true, isCard);
        //     });
        //   } else {
        //     tool.confirm(ret.msg + ' 是否打印 ？', '打印提示').then(() => {
        //       tool.toPrint(printList, true, isCard);
        //     });
        //   }
        // });
      } else {
        tool.toPrint(printList, false, isCard);
      }
    }
      break;
    case 'f10': {
      let transType = tool.xe.toNumber(fApi.value.getValue('transType'))
      let buId = fApi.value.getValue('buId')
      let tval = ''
      if(transType===150501||transType===150502) tval = '进价'
      if (transType === 150601 || transType === 150602 || transType === 150603) tval = '售价'
      let options = {
        title: '历史价格',
        width: 1000,
        height: 700,
        mounted: (api) => {
          setTimeout(() => {
            options.getData(api)
          }, 50)
        },
        rules: [
          {
            field: 'jtab',title:' ',com:'JTab',list:[{id:'进价',name: '进价'},{id:'售价',name: '售价'}],
            defaultValue: tval,width: 260,inject: true,
            events: {
              change: (api, val) => {
                let transType = 150601
                if (val === '进价') transType = 150501
                let ids = []
                let list = fApi.value.getValue('infos')
                list.map(row => {
                  if(row.invId) ids.push(row.invId)
                })
                let formData = api.getFormData()
                tool.post('common/getHistPrice', {
                  transType, buId, ids, currentPage: 1, pageSize: 500,
                  displayLastPrice: formData.displayLastPrice
                }).then(ret => {
                  if (ret.stat) {
                    if (ret.data) {
                      if (ret.data.columns) {
                      }
                      api.exec('grid', 'setData', ret.data.list)
                    }
                  }
                })
              }
            }
          },
          {field: 'buName', title:'客户',com:'JAuto',cat: 'contactList',idField: 'buId',width: 260,},
          {field: 'invName', title:'商品',com: 'JAuto',cat: 'goods',idField: 'invId',width: 260},
          {com: 'newrow'},
          {field: 'displayLastPrice', title:' ',com: 'JCheck',width: 260,label:'显示最后一次价格',defaultValue: true},
          {
            field:'',title:' ',com: 'JButton',text: '查询',width: 120,type: 'info',icon:'search',inject: true,
            events: {
              click: (api) => {
                options.getData(api)
              }
            }
          },
          {
            field: 'grid',title:'',com: 'JGrid',width: 950,height: 600,
            columns: [
              {width: 50,type: 'index'},
              {title: '日期',field: 'billDate', width: 100,sortable: true,align: 'center'},
              {title: '票号',field: 'billNo', width: 120,align: 'left',canClick: true},
              {title: '客户',field: 'buName', width: 200,align: 'left',filter: true,sortable: true,},
              {title: '商品',field: 'invName', width: 200,align: 'left'},
              {title: '业务类型',field: 'transTypeName', width: 90,sortable: true,align: 'center',},
              {title: '规格',field: 'spec', width: 60,align: 'center'},
              {title: '价格',field: 'price', width: 80,sortable: true,align: 'right',formatter:'formatMoney'},
            ]
          }
        ],
        getData: (api) => {
          let formData = api.getFormData()
          let val = formData.jtab
          let transType = 150601
          if (val === '进价') transType = 150501
          let ids = []
          let list = fApi.value.getValue('infos')
          list.map(row => {
            if(row.invId) ids.push(row.invId)
          })
          if(typeof formData.buId !== 'undefined') buId = formData.buId
          tool.post('common/getHistPrice', {
            transType, buId, ids, currentPage: 1, pageSize: 500,
            displayLastPrice: formData.displayLastPrice
          }, true).then(ret => {
            if (ret.stat) {
              if (ret.data) {
                if (ret.data.columns) {
                }
                api.exec('grid', 'setData', ret.data.list)
              }
            }
          })
        }
      }
      tool.editor(options)
    }
      break;
    case 'f9': {
      let id = fApi.value.getValue('id')
      if (!id) {
        return tool.warning('请先保存票据后才可导出')
      }
      tool.post('bill/exportBill', {id: id}).then(ret => {
        if (ret.stat && ret.data) {
          window.open(ret.data)
        }
      })
    }
      break;
  }
}

// 初始化快捷键
const initShortCut = () => {
  // eslint-disable-next-line no-undef
  shortcut.add('alt+1',  (e) => {
    e.stopImmediatePropagation()
    e.preventDefault()
    e.stopPropagation()
    handleClick('formFirstInput')
  })
  shortcut.add('alt+2',  (e) => {
    e.stopImmediatePropagation()
    e.preventDefault()
    e.stopPropagation()
    handleClick('gridFirstEmptyCell')
  })
  // eslint-disable-next-line no-undef
  shortcut.add('ctrl+s',  (e) => {
    e.stopImmediatePropagation()
    e.preventDefault()
    e.stopPropagation()
    fApi.value.exec('infos', 'clearActivated')
    setTimeout(() => {
      handleClick('save')
    }, 10)
  })
  shortcut.add('f1',  (e) => {
    e.stopImmediatePropagation()
    e.preventDefault()
    e.stopPropagation()
    fApi.value.exec('infos', 'clearActivated')
    setTimeout(() => {
      handleClick('save')
    }, 10)
  })
  shortcut.add('f2',  (e) => {
    e.stopImmediatePropagation()
    e.preventDefault()
    e.stopPropagation()
    fApi.value.exec('infos', 'clearActivated')
    setTimeout(() => {
      handleClick('accounted')
    }, 10)

  })
  shortcut.add('f3',  (e) => {
    e.stopImmediatePropagation()
    e.preventDefault()
    e.stopPropagation()
    fApi.value.exec('infos', 'clearActivated')
    tool.confirm('确定退审 ？', '退审提醒').then(() => {
      handleClick('wasted')
    })
  })
  shortcut.add('f4',  (e) => {
    e.stopImmediatePropagation()
    e.preventDefault()
    e.stopPropagation()
    handleClick('print')
  })
  shortcut.add('ctrl+p',  (e) => {
    e.stopImmediatePropagation()
    e.preventDefault()
    e.stopPropagation()
    handleClick('printView')
  })
  shortcut.add('f12',  (e) => {
    e.stopImmediatePropagation()
    e.preventDefault()
    e.stopPropagation()
    fApi.value.exec('infos', 'clearActivated')
    setTimeout(() => {
      handleClick('add')
    }, 10)
  })
  shortcut.add('f8',  (e) => {
    e.stopImmediatePropagation()
    e.preventDefault()
    e.stopPropagation()
    fApi.value.exec('infos', 'clearActivated')
    setTimeout(() => {
      handleClick('copy')
    }, 10)
  })
  // eslint-disable-next-line no-undef
  shortcut.add('F9',  (e) => {
    e.stopImmediatePropagation()
    e.preventDefault()
    e.stopPropagation()
    handleClick('f9')
  })
  shortcut.add('f10',  (e) => {
    e.stopImmediatePropagation()
    e.preventDefault()
    e.stopPropagation()
    handleClick('f10')
  })
  shortcut.add('f11',  (e) => {
    e.stopImmediatePropagation()
    e.preventDefault()
    e.stopPropagation()
    handleClick('del')
  })
}
const itemClick = (item) => {
  handleClick('printView')
}
const handleClick = (type) => {
  if(type === 'formFirstInput') {
    toolClick(type)
  }
  if(type === 'gridFirstEmptyCell') {
    toolClick(type)
  }
  if(type === 'save') {
    if(billState.value === 'ready' || billState.value === 'draft') {
      toolClick(type)
    }
  }

  if(type === 'accounted') {
    if(billState.value === 'ready' || billState.value === 'draft') {
      toolClick(type)
    }
  }
  if(type === 'wasted') {
    if(billState.value === 'accounted') {
      toolClick(type)
    }
  }
  if(type === 'print') {
    if(billState.value === 'draft'||billState.value === 'accounted') {
      toolClick(type)
    }
  }
  if(type === 'printView') {
    if(billState.value === 'draft'||billState.value === 'accounted') {
      toolClick(type)
    }
  }
  if(type === 'del') {
    if(billState.value === 'draft') {
      toolClick(type)
    }
  }
  if(type === 'copy') {
    if(billState.value !== 'ready') {
      toolClick(type)
    }
  }
  if(type === 'f10') {
    toolClick(type)
  }
  if(type === 'f11') {
    toolClick(type)
  }
  if(type === 'f9') {
    toolClick(type)
  }
  if(type === 'add') {
    // if(billState.value  !== 'ready') {
    toolClick(type)
    // }
  }
  if(type === 'list') {
    emit('toList')
  }
}
const removeShort = () => {
  // eslint-disable-next-line no-undef
  shortcut.remove('f1')
  // eslint-disable-next-line no-undef
  shortcut.remove('ctrl+s')
  shortcut.remove('alt+1')
  shortcut.remove('alt+2')
  shortcut.remove('f2')
  shortcut.remove('f3')
  shortcut.remove('f4')
  shortcut.remove('ctrl+p')
  shortcut.remove('f8')
  // eslint-disable-next-line no-undef
  shortcut.remove('F9')
  shortcut.remove('f10')
  shortcut.remove('f11')
  shortcut.remove('f12')
}
onBeforeMount(async () => {
  initShortCut()
  opt.value = await tool.getOptions()
})
onActivated(() => {
  initShortCut()
})
onDeactivated(() => {
  removeShort()
})
onUnmounted(() => {
  removeShort()
})


const setApi = (api) => {
  fApi.value = api
}
defineExpose({setApi})

</script>

<style scoped lang="scss">
.billBottom {
  text-align: left;
  margin-top: 15px;
  .el-button {
    border-radius: 0;
  }
  .el-button-group {
    border-radius: 0;
  }
}
</style>